package org.red5.audio;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.concurrent.ExecutionException;

public abstract class AudioConverter {

	private AudioSettings audioSettings;
	private boolean deleteSource;
	private String sourceFile, destinationDirectory, newFileName;
	
	public AudioConverter(AudioSettings audioSettings, String sourceFile, String destinationDirectory, String newFileName, boolean deleteSourceFile)
	{
		this.audioSettings = audioSettings;
		this.sourceFile = sourceFile;
		this.destinationDirectory = destinationDirectory;
		this.newFileName = newFileName;
	}
	/**
	 * Convert a file from one extension to another.
	 * @throws ExecutionException 
	 */
	// template pattern
	public void convert() throws FileNotFoundException, RuntimeException
	{
		// check if sourcefile and destinationdirectory exist
		File sourcefile = new File(getSourceFile());
		if (!sourcefile.exists() || !sourcefile.isFile()) {
			throw new FileNotFoundException("The source directory " +  getDestinationDirectory() + " could not be found");
		}
		
		File destinationdir = new File(getDestinationDirectory());
		if (!destinationdir.exists() || !destinationdir.isDirectory()) {
			throw new FileNotFoundException("The destination directory " +  getDestinationDirectory() + " could not be found");
		}
		
		// delete destination file if already exists
		//deleteFile(getDestinationDirectory() + getNewFileName());

		// convert
		performConvertion();
		
		// delete file if file is to be deleted
		if(isDeleteSource()) {
			deleteFile(getSourceFile());
		}
	}
	
	/**
	 * This method performs the conversion
	 * @throws RuntimeException if something went wrong
	 */
	protected abstract void performConvertion() throws RuntimeException;
	
	// getters and setters
	public boolean isDeleteSource() {
		return deleteSource;
	}
	
	public void setDeleteSource(boolean deleteSource) {
		this.deleteSource = deleteSource;
	}
	
	public AudioSettings getAudioSettings() {
		return audioSettings;
	}
	public String getSourceFile() {
		return sourceFile;
	}
	public String getDestinationDirectory() {
		return destinationDirectory;
	}
	public String getNewFileName() {
		return newFileName;
	}
	
	// private methods
	protected void deleteFile(String path)
	{
		File f = new File(path);
		if(f.exists()) {
			f.delete();
		}
	}
	
}
